package com.ecar.mp.util;

import com.whalin.MemCached.MemCachedClient;
import com.whalin.MemCached.SockIOPool;
import com.ecar.common.util.PropertyUtil;
import com.ecar.common.util.SpringContextUtil;
import com.ecar.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by 30 on 2016/7/29.
 */
public class MemCacheUtil {

	private static final Logger log = LoggerFactory.getLogger(MemCacheUtil.class);

	private static String SERVERS;
	private static MemCachedClient mc = null;
	private static MemCacheUtil instance = new MemCacheUtil();

	public static MemCacheUtil getInstance() {
		return instance;
	}

	private MemCacheUtil() {
		if (mc == null) {
			PropertyUtil propertyUtil = (PropertyUtil) SpringContextUtil.getBean("propertyUtil");
			MemCacheUtil.SERVERS = propertyUtil.getValue("config.memcache.servers");
			if (StringUtil.isNotEmpty(SERVERS)) {
				log.info("连接Memcache服务：" + SERVERS);
				String[] servers = SERVERS.split(",");
				SockIOPool pool = SockIOPool.getInstance();
				pool.setServers(servers);
				pool.setFailover(true);
				pool.setInitConn(10);
				pool.setMinConn(5);
				pool.setMaxConn(250);
				pool.setMaintSleep(30);
				pool.setNagle(false);
				pool.setSocketTO(3000);
				pool.setAliveCheck(true);
				pool.initialize();

				mc = new MemCachedClient();
			}
		}
	}

	public void set(String key, Object obj) {
		if (mc == null) return;
		mc.set(key, obj);
	}

	public void set(String key, Object obj, int expire) {
		if (mc == null) return;
		mc.set(key, obj, expire);
	}

	public Object get(String key) {
		if (mc == null) return null;
		return mc.get(key);
	}

	public void remove(String key) {
		if (mc == null) return;
		mc.delete(key);
	}
}
